package GUI;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.*;
import javax.swing.border.EmptyBorder;

import java.awt.*;

import java.awt.Component;
import javax.swing.border.TitledBorder;
import model.Debtor;
import control.PersonCtrl;

import java.awt.event.*;

import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class debtors extends JFrame {

	private final TableRowSorter<TableModel> sorter;
	private JPanel contentPane;
	private JTextField tfDcpr;
	private JTable debtorsTable;
	private JTextField tfDname;
	private JTextField tfDaddress;
	private JTextField tfDzipCode;
	private JTextField tfDcity;
	private JTextField tfDphone;
	private JTextField tfDgsm;
	private JTextField tfDemail;
	private JTextField tfDcontactCpr;
	private PersonCtrl personCtrl = new PersonCtrl();
	private debtorsTable debtorsT = new debtorsTable();
	private JTextField tfSearch;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					debtors frame = new debtors();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public debtors() {
		setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\Andrada\\Desktop\\images.jpg"));
		setTitle("DEBTORS MENU");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 1050, 600);
		contentPane = new JPanel();
		contentPane.setBackground(new Color(255, 255, 153));
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JPanel mainDpanel = new JPanel();
		mainDpanel.setBackground(new Color(255, 255, 153));
		mainDpanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Debtor Control", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		mainDpanel.setBounds(712, 50, 312, 501);
		contentPane.add(mainDpanel);
		mainDpanel.setLayout(null);
		
		
		JButton btnDadd = new JButton("Add");
		btnDadd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(ifEmpty()) return;
                if(ifDebtorExists())
        		{
        			JOptionPane.showMessageDialog(null,"Debtor with this CPR already exists.");
        			return;
        		}
                if(ifContactExists() == false)
                {
                	JOptionPane.showMessageDialog(null,"Contact with this CPR does not exist.");
        			return;
                }
                try 
                {
                	if(!ifPersonExists())
                	{
                        personCtrl.createPerson(tfDname.getText(), tfDaddress.getText(), tfDzipCode.getText(), tfDcity.getText(),
                                                 tfDphone.getText(), tfDgsm.getText(), tfDemail.getText(), tfDcpr.getText());
                        personCtrl.createDebtor(tfDcpr.getText(), tfDcontactCpr.getText());
                        updateDebtorTable();
                        clearTextFields();
                        JOptionPane.showMessageDialog(null,"Debtor has been successfully created.");
                	}
                	else
                	{
                		 personCtrl.updatePerson(tfDname.getText(), tfDaddress.getText(), tfDzipCode.getText(), tfDcity.getText(),
                                tfDphone.getText(), tfDgsm.getText(), tfDemail.getText(), tfDcpr.getText());
                		 personCtrl.createDebtor(tfDcpr.getText(), tfDcontactCpr.getText());
                         updateDebtorTable();
                         clearTextFields();
                         JOptionPane.showMessageDialog(null,"Debtor has been successfully created.");
                	}
                } 
                catch (Exception r) 
                {
                        JOptionPane.showMessageDialog(null,"Error in creating Debtor.");
                }
				
			}
		});
		btnDadd.setBounds(10, 459, 90, 31);
		mainDpanel.add(btnDadd);
		btnDadd.setFont(new Font("Times New Roman", Font.BOLD, 17));
		
		JButton btnDupdate = new JButton("Update");
		btnDupdate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(ifEmpty()) return;
    			if(ifDebtorExists() == false)
        		{
        			JOptionPane.showMessageDialog(null,"Debtor with this CVR does not exist.");
        			return;
        		}
    			if(ifContactExists() == false)
                {
                	JOptionPane.showMessageDialog(null,"Contact with this CPR does not exist.");
        			return;
                }
    			try
    			{
    				personCtrl.updateDebtor(tfDcpr.getText(), tfDname.getText(), tfDaddress.getText(), tfDzipCode.getText(), tfDcity.getText(),
                                             tfDphone.getText(), tfDgsm.getText(), tfDemail.getText(), tfDcontactCpr.getText());
    				updateDebtorTable();
    				clearTextFields();
                    JOptionPane.showMessageDialog(null,"Debtor has been successfuly updated.");
    			}
    			catch(Exception r)
    			{
    				JOptionPane.showMessageDialog(null,"Error in updating Debtor.");
    			}
			}
		});
		btnDupdate.setBounds(110, 460, 90, 31);
		mainDpanel.add(btnDupdate);
		btnDupdate.setFont(new Font("Times New Roman", Font.BOLD, 17));
		
		JButton btnDdelete = new JButton("Delete");
		btnDdelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(ifDebtorExists() == false)
        		{
        			JOptionPane.showMessageDialog(null,"Debtor with this CPR does not exist. Enter a valid CPR or double click table row.");
        			return;
        		}
                try
                {
                	if(personCtrl.deleteDebtor(tfDcpr.getText()))
                		JOptionPane.showMessageDialog(null,"Debtor has been successfully deleted.");
                	else
                		JOptionPane.showMessageDialog(null,"Cannot delete debtor.");    
                    updateDebtorTable();
                    clearTextFields();
                }
                catch(Exception r)
                {
                        JOptionPane.showMessageDialog(null,"Error in deleting Debtor.");
                }
			}
		});
		btnDdelete.setBounds(210, 460, 90, 31);
		mainDpanel.add(btnDdelete);
		btnDdelete.setFont(new Font("Times New Roman", Font.BOLD, 17));
		
		tfDcpr = new JTextField();
		tfDcpr.setBounds(130, 20, 170, 25);
		mainDpanel.add(tfDcpr);
		tfDcpr.setColumns(10);
		
		JLabel lblDcpr = new JLabel("CPR :");
		lblDcpr.setBounds(38, 16, 82, 31);
		mainDpanel.add(lblDcpr);
		lblDcpr.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDcpr.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		JLabel lblDname = new JLabel("Name :");
		lblDname.setBounds(38, 58, 82, 31);
		mainDpanel.add(lblDname);
		lblDname.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDname.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		tfDname = new JTextField();
		tfDname.setBounds(130, 62, 170, 25);
		mainDpanel.add(tfDname);
		tfDname.setColumns(10);
		
		JLabel lblDaddress = new JLabel("Address :");
		lblDaddress.setBounds(38, 100, 82, 31);
		mainDpanel.add(lblDaddress);
		lblDaddress.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDaddress.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		tfDaddress = new JTextField();
		tfDaddress.setBounds(130, 104, 170, 25);
		mainDpanel.add(tfDaddress);
		tfDaddress.setColumns(10);
		
		tfDzipCode = new JTextField();
		tfDzipCode.setBounds(130, 146, 170, 25);
		mainDpanel.add(tfDzipCode);
		tfDzipCode.setColumns(10);
		
		JLabel lblDzipCode = new JLabel("Zip Code :");
		lblDzipCode.setBounds(38, 142, 82, 31);
		mainDpanel.add(lblDzipCode);
		lblDzipCode.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDzipCode.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		JLabel lblDcity = new JLabel("City :");
		lblDcity.setBounds(38, 184, 82, 31);
		mainDpanel.add(lblDcity);
		lblDcity.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDcity.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		tfDcity = new JTextField();
		tfDcity.setBounds(130, 188, 170, 25);
		mainDpanel.add(tfDcity);
		tfDcity.setColumns(10);
		
		tfDphone = new JTextField();
		tfDphone.setBounds(130, 230, 170, 25);
		mainDpanel.add(tfDphone);
		tfDphone.setColumns(10);
		
		JLabel lblDphone = new JLabel("Phone :");
		lblDphone.setBounds(38, 226, 82, 31);
		mainDpanel.add(lblDphone);
		lblDphone.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDphone.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		JLabel lblDgsm = new JLabel("GSM :");
		lblDgsm.setBounds(38, 268, 82, 31);
		mainDpanel.add(lblDgsm);
		lblDgsm.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDgsm.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		tfDgsm = new JTextField();
		tfDgsm.setBounds(130, 272, 170, 25);
		mainDpanel.add(tfDgsm);
		tfDgsm.setColumns(10);
		
		JLabel lblDemail = new JLabel("Email :");
		lblDemail.setBounds(38, 310, 82, 31);
		mainDpanel.add(lblDemail);
		lblDemail.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDemail.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		tfDemail = new JTextField();
		tfDemail.setBounds(130, 314, 170, 25);
		mainDpanel.add(tfDemail);
		tfDemail.setColumns(10);
		
		tfDcontactCpr = new JTextField();
		tfDcontactCpr.setColumns(10);
		tfDcontactCpr.setBounds(130, 356, 170, 25);
		mainDpanel.add(tfDcontactCpr);
		
		JLabel lblDcontact = new JLabel("Contact CPR : ");
		lblDcontact.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDcontact.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		lblDcontact.setBounds(10, 352, 110, 31);
		mainDpanel.add(lblDcontact);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 81, 692, 470);
		contentPane.add(scrollPane);
		
		debtorsTable = new JTable();
		
		debtorsTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][]{},
                new String []
                {
                            "Name", "Address", "Zipcode", "City", "Phone", "GSM", "E-mail", "CPR", "Contact CPR"
                }));
		sorter = new TableRowSorter<TableModel>(debtorsT);
		debtorsTable.setRowSorter(sorter);
		scrollPane.setViewportView(debtorsTable);
		
		JLabel lblListOfDebtors = new JLabel("LIST OF DEBTORS");
		lblListOfDebtors.setHorizontalAlignment(SwingConstants.CENTER);
		lblListOfDebtors.setFont(new Font("Times New Roman", Font.BOLD, 15));
		lblListOfDebtors.setBounds(10, 7, 692, 31);
		contentPane.add(lblListOfDebtors);
		
		JLabel lblManageDebtors = new JLabel("MANAGE DEBTORS");
		lblManageDebtors.setHorizontalAlignment(SwingConstants.CENTER);
		lblManageDebtors.setFont(new Font("Times New Roman", Font.BOLD, 15));
		lblManageDebtors.setBounds(712, 7, 312, 31);
		contentPane.add(lblManageDebtors);
		
		JLabel lblSearch = new JLabel("Search :");
		lblSearch.setBounds(10, 42, 110, 30);
		contentPane.add(lblSearch);
		lblSearch.setHorizontalAlignment(SwingConstants.RIGHT);
		lblSearch.setFont(new Font("Times New Roman", Font.PLAIN, 15));
		
		tfSearch = new JTextField();
		tfSearch.setBounds(130, 45, 130, 25);
		contentPane.add(tfSearch);
		tfSearch.setColumns(10);
		tfSearch.getDocument().addDocumentListener(new DocumentListener() {  // <---
            @Override
            public void removeUpdate(DocumentEvent e) {
                filter();
            }
             
            @Override
            public void insertUpdate(DocumentEvent e) {
                filter();
            }
             
            @Override
            public void changedUpdate(DocumentEvent e) {}
        });
		
		debtorsTable.addMouseListener(new MouseAdapter() {
	      	  public void mouseClicked(MouseEvent e) {
	      	    if (e.getClickCount() == 2) {
	      	      JTable target = (JTable)e.getSource();
	      	      int row = target.getSelectedRow();
	      	      setDebtorFields((String)debtorsTable.getModel().getValueAt(row, 7));
	      	    }
	      	  }
	      	});
	}
	
	public void setDebtorFields(String cpr)
    {
    	 Debtor debtor = personCtrl.getDebtorByCpr(cpr);
    	 tfDcpr.setText(debtor.getCpr());
         tfDname.setText(debtor.getName());
         tfDaddress.setText(debtor.getAddress());
         tfDzipCode.setText(debtor.getZipCode());
         tfDcity.setText(debtor.getCity());
         tfDphone.setText(debtor.getPhone());
         tfDgsm.setText(debtor.getGsm());
         tfDemail.setText(debtor.getEmail());
         tfDcontactCpr.setText(debtor.getContact().getCpr());
    }
	
	public boolean ifEmpty()
    {
            if(tfDcpr.getText().equals("") || tfDname.getText().equals("") || tfDaddress.getText().equals("") || tfDzipCode.getText().equals("") ||
              tfDcity.getText().equals("") || tfDphone.getText().equals("") || tfDgsm.getText().equals("") || tfDemail.getText().equals("") || tfDcontactCpr.getText().equals(""))
            {
                    JOptionPane.showMessageDialog(null,"Some of the fields are empty.");
                    return true;
            }
            return false;
    }
	
	public boolean ifDebtorExists()
    {
    	if(personCtrl.getDebtorByCpr(tfDcpr.getText()) != null)
    		return true;
    	return false;
    }
	
	public boolean ifPersonExists()
    {
    	if(personCtrl.getPersonByCpr(tfDcpr.getText()) != null)
    		return true;
    	return false;
    }
	
	public boolean ifContactExists()
    {
    	if(personCtrl.getContactByCpr(tfDcontactCpr.getText()) != null)
    		return true;
    	return false;
    }
	
	 public void clearTextFields()
     {
             tfDcpr.setText("");
             tfDname.setText("");
             tfDaddress.setText("");
             tfDzipCode.setText("");
             tfDcity.setText("");
             tfDphone.setText("");
             tfDgsm.setText("");
             tfDemail.setText("");
             tfDcontactCpr.setText("");
     }
	 
	 public void updateDebtorTable()
     {
     debtorsT.setDebtor(personCtrl.listAllDebtors());
     debtorsTable.setModel(debtorsT);
     }
	 
	 protected void filter()
	 {
		 sorter.setRowFilter(RowFilter.regexFilter("^(?i)"+tfSearch.getText()));
	 }
}
